<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分页表单系统</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.7.2/css/all.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', Arial, sans-serif;
            padding: 20px;
            background-color: #f5f7fa;
            color: #606266;
            line-height: 1.5;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #ebeef5;
        }

        .header h1 {
            color: #303133;
            margin-bottom: 20px;
            font-size: 24px;
            font-weight: 500;
        }

        .toolbar {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 20px;
            align-items: center;
        }

        .search-section {
            display: flex;
            gap: 12px;
            flex: 1;
            min-width: 300px;
        }

        .button-group {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        .search-input {
            flex: 1;
            padding: 11px 15px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
            transition: border-color 0.2s;
            background-color: #fff;
            min-width: 0;
        }

        .search-input:focus {
            outline: none;
            border-color: #409eff;
        }

        .btn {
            padding: 11px 20px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s;
            white-space: nowrap;
            outline: none;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        /* Element UI 风格按钮 */
        .btn-primary {
            background-color: #409eff;
            border-color: #409eff;
            color: white;
        }

        .btn-primary:hover {
            background-color: #66b1ff;
            border-color: #66b1ff;
        }

        .btn-primary:active {
            background-color: #3a8ee6;
            border-color: #3a8ee6;
            outline: none;
        }

        .btn-success {
            background-color: #67c23a;
            border-color: #67c23a;
            color: white;
        }

        .btn-success:hover {
            background-color: #85ce61;
            border-color: #85ce61;
        }

        .btn-success:active {
            background-color: #5daf34;
            border-color: #5daf34;
            outline: none;
        }

        .btn-danger {
            background-color: #f56c6c;
            border-color: #f56c6c;
            color: white;
        }

        .btn-danger:hover {
            background-color: #f78989;
            border-color: #f78989;
        }

        .btn-danger:active {
            background-color: #dd6161;
            border-color: #dd6161;
            outline: none;
        }

        .btn-warning {
            background-color: #e6a23c;
            border-color: #e6a23c;
            color: white;
        }

        .btn-warning:hover {
            background-color: #ebb563;
            border-color: #ebb563;
        }

        .btn-warning:active {
            background-color: #cf9236;
            border-color: #cf9236;
            outline: none;
        }

        .btn-info {
            background-color: #909399;
            border-color: #909399;
            color: white;
        }

        .btn-info:hover {
            background-color: #a6a9ad;
            border-color: #a6a9ad;
        }

        .btn-info:active {
            background-color: #82848a;
            border-color: #82848a;
            outline: none;
        }

        .btn-text {
            background-color: transparent;
            border-color: transparent;
            color: #409eff;
        }

        .btn-text:hover {
            background-color: #ecf5ff;
            border-color: #b3d8ff;
            color: #66b1ff;
        }

        .btn-sm {
            padding: 7px 15px;
            font-size: 12px;
        }

        .table-container {
            overflow-x: auto;
            margin-bottom: 20px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            font-size: 14px;
        }

        th,
        td {
            padding: 12px 0;
            text-align: left;
            border-bottom: 1px solid #ebeef5;
        }

        th {
            background-color: #fafafa;
            font-weight: 500;
            color: #909399;
            padding: 15px 0;
        }

        td {
            color: #606266;
        }

        tr:hover {
            background-color: #fafafa;
        }

        .actions {
            display: flex;
            gap: 8px;
        }

        .pagination {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 0;
            border-top: 1px solid #ebeef5;
            flex-wrap: wrap;
            gap: 15px;
        }

        .page-info {
            font-size: 14px;
            color: #606266;
        }

        .page-controls {
            display: flex;
            gap: 8px;
            align-items: center;
            flex-wrap: wrap;
        }

        .page-select {
            padding: 7px 10px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
            background-color: #fff;
            color: #606266;
        }

        .page-select:focus {
            outline: none;
            border-color: #409eff;
        }

        .page-numbers {
            display: flex;
            gap: 4px;
        }

        .page-btn {
            padding: 7px 12px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            background-color: white;
            cursor: pointer;
            min-width: 36px;
            text-align: center;
        }

        .page-btn:hover {
            background-color: #ecf5ff;
            border-color: #b3d8ff;
        }

        .page-btn.active {
            background-color: #409eff;
            border-color: #409eff;
            color: white;
        }

        .page-btn.disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .jump-section {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .jump-input {
            width: 60px;
            padding: 7px 10px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            text-align: center;
        }

        .jump-input:focus {
            outline: none;
            border-color: #409eff;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 20px;
            border-radius: 4px;
            width: 90%;
            max-width: 600px;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #ebeef5;
        }

        .modal-header h2 {
            margin: 0;
            color: #303133;
            font-size: 18px;
            font-weight: 500;
        }

        .close {
            font-size: 24px;
            cursor: pointer;
            color: #909399;
            transition: color 0.2s;
        }

        .close:hover {
            color: #409eff;
        }

        .form-group {
            margin-bottom: 22px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #606266;
            font-size: 14px;
        }

        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 11px 15px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
            transition: border-color 0.2s;
            background-color: #fff;
        }

        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #409eff;
        }

        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }

        .form-actions {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            margin-top: 20px;
            padding-top: 15px;
            border-top: 1px solid #ebeef5;
        }

        .disabled {
            pointer-events: none;
            opacity: 0.6;
        }

        /* 扇形图样式 */
        .chart-container {
            width: 100%;
            height: 400px;
            position: relative;
            margin: 20px 0;
        }

        .chart-legend {
            margin-top: 20px;
        }

        .legend-item {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .legend-color {
            width: 16px;
            height: 16px;
            border-radius: 2px;
            margin-right: 10px;
            flex-shrink: 0;
        }

        .legend-text {
            font-size: 14px;
            color: #606266;
        }

        .chart-title {
            text-align: center;
            font-size: 18px;
            font-weight: 500;
            margin-bottom: 20px;
            color: #303133;
        }

        /* 文件上传样式 */
        .file-input-wrapper {
            position: relative;
            overflow: hidden;
            display: inline-block;
            width: 100%;
        }

        .file-input-wrapper input[type=file] {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }

        /* 图标样式 */
        .fa-icon {
            font-size: 14px;
            width: 14px;
            text-align: center;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            body {
                padding: 15px;
            }

            .container {
                padding: 15px;
            }

            .toolbar {
                flex-direction: column;
                align-items: stretch;
                gap: 15px;
            }

            .search-section {
                min-width: auto;
            }

            .button-group {
                justify-content: center;
            }

            .actions {
                flex-direction: column;
            }

            .pagination {
                flex-direction: column;
                gap: 15px;
            }

            .modal-content {
                width: 95%;
                max-width: 95%;
                margin: 10% auto;
                padding: 15px;
            }

            .header h1 {
                font-size: 20px;
            }

            .modal-header h2 {
                font-size: 16px;
            }
        }

        @media (max-width: 480px) {
            body {
                padding: 10px;
            }

            .container {
                padding: 12px;
            }

            .btn {
                padding: 9px 15px;
                font-size: 13px;
            }

            .btn-sm {
                padding: 6px 12px;
                font-size: 12px;
            }

            table {
                font-size: 12px;
            }

            th,
            td {
                padding: 8px 0;
            }

            .form-group {
                margin-bottom: 18px;
            }

            .form-group label {
                font-size: 13px;
            }

            .form-group input,
            .form-group textarea {
                padding: 9px 12px;
                font-size: 13px;
            }

            .page-controls {
                flex-direction: column;
                align-items: stretch;
            }

            .page-numbers {
                justify-content: center;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <h1 id="page-title">数据管理系统</h1>
        </div>

        <div class="toolbar">
            <div class="search-section">
                <input type="text" class="search-input" id="search-input" placeholder="请输入搜索内容...">
                <button class="btn btn-primary" id="search-btn">
                    <i class="fas fa-search fa-icon"></i>
                    搜索
                </button>
                <button class="btn btn-info" id="reset-btn">
                    <i class="fas fa-redo fa-icon"></i>
                    重置
                </button>
            </div>
            <div class="button-group">
                <button class="btn btn-info" id="stats-btn" style="display: none;">
                    <i class="fas fa-chart-bar fa-icon"></i>
                    <span id="stats-btn-text">统计</span>
                </button>
                <button class="btn btn-success" id="import-btn" style="display: none;">
                    <i class="fas fa-file-import fa-icon"></i>
                    <span id="import-btn-text">导入</span>
                </button>
                <button class="btn btn-primary" id="export-btn" style="display: none;">
                    <i class="fas fa-file-export fa-icon"></i>
                    <span id="export-btn-text">导出</span>
                </button>
                <button class="btn btn-primary" id="add-btn">
                    <i class="fas fa-plus fa-icon"></i>
                    新增
                </button>
            </div>
        </div>

        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th style="width: 60px; padding-left: 15px;">ID</th>
                        <th id="col-text1">文本1</th>
                        <th id="col-text2">文本2</th>
                        <th id="col-textarea1">文本域1</th>
                        <th id="col-createtime">创建时间</th>
                        <th style="width: 180px; padding-right: 15px;">操作</th>
                    </tr>
                </thead>
                <tbody id="table-body">
                </tbody>
            </table>
        </div>

        <div class="pagination">
            <div class="page-info" id="page-info">
                显示第 1 到 10 条记录，共 0 条记录
            </div>
            <div class="page-controls">
                <select class="page-select" id="page-size">
                    <option value="10">10条/页</option>
                    <option value="20">20条/页</option>
                    <option value="50">50条/页</option>
                </select>
                <button class="btn btn-info" id="prev-btn">
                    <i class="fas fa-chevron-left fa-icon"></i>
                    上一页
                </button>
                <div class="page-numbers" id="page-numbers"></div>
                <button class="btn btn-info" id="next-btn">
                    下一页
                    <i class="fas fa-chevron-right fa-icon"></i>
                </button>
                <div class="jump-section">
                    <span>跳转到</span>
                    <input type="number" class="jump-input" id="jump-input" min="1">
                    <span>页</span>
                    <button class="btn btn-info btn-sm" id="jump-btn">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增/修改弹窗 -->
    <div class="modal" id="edit-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="edit-modal-title">新增数据</h2>
                <span class="close">&times;</span>
            </div>
            <form id="edit-form">
                <input type="hidden" id="edit-id">
                <div class="form-group">
                    <label for="edit-text1" id="label-text1">文本1</label>
                    <input type="text" id="edit-text1" required>
                </div>
                <div class="form-group">
                    <label for="edit-text2" id="label-text2">文本2</label>
                    <input type="text" id="edit-text2" required>
                </div>
                <div class="form-group">
                    <label for="edit-textarea1" id="label-textarea1">文本域1</label>
                    <textarea id="edit-textarea1" required></textarea>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-info" id="cancel-edit">
                        <i class="fas fa-times fa-icon"></i>
                        取消
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save fa-icon"></i>
                        保存
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 详情弹窗 -->
    <div class="modal" id="detail-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>详情信息/明细查询</h2>
                <span class="close">&times;</span>
            </div>
            <div id="detail-content">
                <div class="form-group">
                    <label id="detail-label-text1">文本1:</label>
                    <div id="detail-text1"></div>
                </div>
                <div class="form-group">
                    <label id="detail-label-text2">文本2:</label>
                    <div id="detail-text2"></div>
                </div>
                <div class="form-group">
                    <label id="detail-label-textarea1">文本域1:</label>
                    <div id="detail-textarea1"></div>
                </div>
                <div class="form-group">
                    <label id="detail-label-createtime">创建时间:</label>
                    <div id="detail-createtime"></div>
                </div>
            </div>
            <div class="form-actions">
                <button class="btn btn-info" id="close-detail">
                    <i class="fas fa-check fa-icon"></i>
                    关闭
                </button>
            </div>
        </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div class="modal" id="delete-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>确认删除</h2>
                <span class="close">&times;</span>
            </div>
            <p style="margin: 20px 0; color: #606266;">确定要删除这条记录吗？此操作不可恢复。</p>
            <div class="form-actions">
                <button class="btn btn-info" id="cancel-delete">
                    <i class="fas fa-times fa-icon"></i>
                    取消
                </button>
                <button class="btn btn-danger" id="confirm-delete">
                    <i class="fas fa-trash fa-icon"></i>
                    确定删除
                </button>
            </div>
        </div>
    </div>

    <!-- 统计弹窗 -->
    <div class="modal" id="stats-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="stats-modal-title">数据统计</h2>
                <span class="close">&times;</span>
            </div>
            <div class="chart-title" id="chart-title">文本1分布统计</div>
            <div class="chart-container">
                <canvas id="stats-chart" width="400" height="400"></canvas>
            </div>
            <div class="chart-legend" id="chart-legend"></div>
            <div class="form-actions">
                <button class="btn btn-info" id="close-stats">
                    <i class="fas fa-check fa-icon"></i>
                    关闭
                </button>
            </div>
        </div>
    </div>

    <!-- 导入弹窗 -->
    <div class="modal" id="import-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>导入数据</h2>
                <span class="close">&times;</span>
            </div>
            <div class="form-group">
                <label>选择CSV文件:</label>
                <div class="file-input-wrapper">
                    <button class="btn btn-info" style="width: 100%;">
                        <i class="fas fa-folder-open fa-icon"></i>
                        选择文件
                    </button>
                    <input type="file" id="import-file" accept=".csv">
                </div>
                <div id="import-file-name" style="margin-top: 10px; font-size: 12px; color: #909399;"></div>
            </div>
            <div class="form-group">
                <label>
                    <input type="checkbox" id="import-clear-existing"> 导入前清空现有数据
                </label>
            </div>
            <div class="form-actions">
                <button type="button" class="btn btn-info" id="cancel-import">
                    <i class="fas fa-times fa-icon"></i>
                    取消
                </button>
                <button type="button" class="btn btn-primary" id="confirm-import">
                    <i class="fas fa-file-import fa-icon"></i>
                    导入
                </button>
            </div>
        </div>
    </div>

    <script>
        // ==================== 配置区域 ====================
        // 使用var方便注册到window
        // 页面标题
        var PAGE_TITLE = "数据管理系统";

        // 列名配置
        var COLUMN_TEXT1 = "姓名";
        var COLUMN_TEXT2 = "邮箱";
        var COLUMN_TEXTAREA1 = "描述";
        var COLUMN_CREATETIME = "创建时间";

        // 按钮配置
        // var SEARCH_PLACEHOLDER = `搜索${COLUMN_TEXT1}...`;
        var STATS_BUTTON_ENABLED = true; // 是否启用统计按钮
        var STATS_BUTTON_TEXT = "统计";
        // var CHART_TITLE = `${COLUMN_TEXT1}分布统计`;

        // 导入导出配置
        var IMPORT_EXPORT_ENABLED = true; // 是否启用导入导出功能
        var IMPORT_BUTTON_TEXT = "导入";
        var EXPORT_BUTTON_TEXT = "导出";

        // 数据库配置
        const DB_NAME = "FormDataDB";
        var STORE_NAME = "formData";

        // 初始化数据
        var INITIAL_DATA = [
            // {
            //     text1: "张三",
            //     text2: "zhangsan@example.com",
            //     textarea1: "这是张三的详细描述信息",
            //     createtime: new Date().toISOString()
            // },
            // {
            //     text1: "李四",
            //     text2: "lisi@example.com",
            //     textarea1: "这是李四的详细描述信息",
            //     createtime: new Date(Date.now() - 86400000).toISOString()
            // },
            // {
            //     text1: "王五",
            //     text2: "wangwu@example.com",
            //     textarea1: "这是王五的详细描述信息",
            //     createtime: new Date(Date.now() - 172800000).toISOString()
            // },
            // {
            //     text1: "张三",
            //     text2: "zhangsan2@example.com",
            //     textarea1: "另一个张三的描述",
            //     createtime: new Date(Date.now() - 259200000).toISOString()
            // },
            // {
            //     text1: "赵六",
            //     text2: "zhaoliu@example.com",
            //     textarea1: "这是赵六的描述",
            //     createtime: new Date(Date.now() - 345600000).toISOString()
            // }
        ];
        // ==================== 配置区域结束 ====================

        // 从参数获取配置
        function getConfig() {
            console.log(window.location)
            // 获取查询字符串
            const queryString = window.location.search;
            // 创建一个空对象来存储参数
            const params = {};
            // 去掉查询字符串的开头的问号
            const pairs = queryString.substring(1).split('&');

            for (let i = 0; i < pairs.length; i++) {
                const pair = pairs[i].split('=');
                // 解码参数名称和值
                const name = decodeURIComponent(pair[0]);
                const value = decodeURIComponent(pair[1] || '');

                params[name] = value;
                window[name] = value;
            }

            // return params;
        }

        // 设置初始化数据
        function setInitData() {
            let d = localStorage.getItem(STORE_NAME)
            if (d) {
                const data = JSON.parse(d)
                window.INITIAL_DATA = data
                localStorage.removeItem(STORE_NAME)
            }


        }

        // 全局变量
        let db = null;
        let currentPage = 1;
        let pageSize = 10;
        let totalRecords = 0;
        let currentData = [];
        let deleteId = null;
        let searchKeyword = '';
        let importFile = null;
        let chartColors = [
            '#409eff', '#67c23a', '#e6a23c', '#f56c6c',
            '#909399', '#409eff', '#67c23a', '#e6a23c',
            '#f56c6c', '#909399', '#409eff', '#67c23a'
        ];

        // DOM元素
        const elements = {
            pageTitle: document.getElementById('page-title'),
            searchInput: document.getElementById('search-input'),
            searchBtn: document.getElementById('search-btn'),
            resetBtn: document.getElementById('reset-btn'),
            statsBtn: document.getElementById('stats-btn'),
            importBtn: document.getElementById('import-btn'),
            exportBtn: document.getElementById('export-btn'),
            addBtn: document.getElementById('add-btn'),
            tableBody: document.getElementById('table-body'),
            pageInfo: document.getElementById('page-info'),
            pageSize: document.getElementById('page-size'),
            prevBtn: document.getElementById('prev-btn'),
            nextBtn: document.getElementById('next-btn'),
            pageNumbers: document.getElementById('page-numbers'),
            jumpInput: document.getElementById('jump-input'),
            jumpBtn: document.getElementById('jump-btn'),
            pageNum: document.getElementById('page-num'),
            colText1: document.getElementById('col-text1'),
            colText2: document.getElementById('col-text2'),
            colTextarea1: document.getElementById('col-textarea1'),
            colCreatetime: document.getElementById('col-createtime'),
            // 弹窗相关
            editModal: document.getElementById('edit-modal'),
            detailModal: document.getElementById('detail-modal'),
            deleteModal: document.getElementById('delete-modal'),
            statsModal: document.getElementById('stats-modal'),
            importModal: document.getElementById('import-modal'),
            editForm: document.getElementById('edit-form'),
            editModalTitle: document.getElementById('edit-modal-title'),
            statsModalTitle: document.getElementById('stats-modal-title'),
            chartTitle: document.getElementById('chart-title'),
            // 按钮文本
            statsBtnText: document.getElementById('stats-btn-text'),
            importBtnText: document.getElementById('import-btn-text'),
            exportBtnText: document.getElementById('export-btn-text'),
            // 表单字段
            editId: document.getElementById('edit-id'),
            editText1: document.getElementById('edit-text1'),
            editText2: document.getElementById('edit-text2'),
            editTextarea1: document.getElementById('edit-textarea1'),
            // 详情显示
            detailText1: document.getElementById('detail-text1'),
            detailText2: document.getElementById('detail-text2'),
            detailTextarea1: document.getElementById('detail-textarea1'),
            detailCreatetime: document.getElementById('detail-createtime'),
            // 图表相关
            statsChart: document.getElementById('stats-chart'),
            chartLegend: document.getElementById('chart-legend'),
            // 导入相关
            importFileInput: document.getElementById('import-file'),
            importFileName: document.getElementById('import-file-name'),
            importClearExisting: document.getElementById('import-clear-existing'),
            // 标签
            labelText1: document.getElementById('label-text1'),
            labelText2: document.getElementById('label-text2'),
            labelTextarea1: document.getElementById('label-textarea1'),
            detailLabelText1: document.getElementById('detail-label-text1'),
            detailLabelText2: document.getElementById('detail-label-text2'),
            detailLabelTextarea1: document.getElementById('detail-label-textarea1'),
            detailLabelCreatetime: document.getElementById('detail-label-createtime')
        };

        // 初始化应用
        function initApp() {
            // 设置页面标题和列名
            elements.pageTitle.textContent = PAGE_TITLE;
            elements.colText1.textContent = COLUMN_TEXT1;
            elements.colText2.textContent = COLUMN_TEXT2;
            elements.colTextarea1.textContent = COLUMN_TEXTAREA1;
            elements.colCreatetime.textContent = COLUMN_CREATETIME;

            // 设置搜索框占位符
            elements.searchInput.placeholder = `搜索/检索${COLUMN_TEXT1}...`; //SEARCH_PLACEHOLDER;

            // 设置按钮文本
            elements.statsBtnText.textContent = STATS_BUTTON_TEXT;
            elements.statsModalTitle.textContent = STATS_BUTTON_TEXT;
            elements.chartTitle.textContent = `${COLUMN_TEXT1}分布统计`; //CHART_TITLE;

            // 设置导入导出按钮文本
            elements.importBtnText.textContent = IMPORT_BUTTON_TEXT;
            elements.exportBtnText.textContent = EXPORT_BUTTON_TEXT;

            // 设置表单标签
            elements.labelText1.textContent = COLUMN_TEXT1;
            elements.labelText2.textContent = COLUMN_TEXT2;
            elements.labelTextarea1.textContent = COLUMN_TEXTAREA1;
            elements.detailLabelText1.textContent = COLUMN_TEXT1 + ':';
            elements.detailLabelText2.textContent = COLUMN_TEXT2 + ':';
            elements.detailLabelTextarea1.textContent = COLUMN_TEXTAREA1 + ':';
            elements.detailLabelCreatetime.textContent = COLUMN_CREATETIME + ':';

            // 控制统计按钮显示
            if (STATS_BUTTON_ENABLED) {
                elements.statsBtn.style.display = 'inline-flex';
            }

            // 控制导入导出按钮显示
            if (IMPORT_EXPORT_ENABLED) {
                elements.importBtn.style.display = 'inline-flex';
                elements.exportBtn.style.display = 'inline-flex';
            }

            // 打开数据库
            openDatabase().then(() => {
                // 绑定事件
                bindEvents();
                // 加载数据
                loadData();
            }).catch(error => {
                console.error('数据库初始化失败:', error);
                alert('数据库初始化失败，请刷新页面重试');
            });
        }

        // 获取当前数据库版本
        function getCurrentDBVersion() {
            const versionKey = `${DB_NAME}_version`;
            let version = localStorage.getItem(versionKey);
            if (!version) {
                version = "1";
                localStorage.setItem(versionKey, version);
            }
            return parseInt(version);
        }

        // 更新数据库版本
        function updateDBVersion(newVersion) {
            const versionKey = `${DB_NAME}_version`;
            localStorage.setItem(versionKey, newVersion.toString());
        }

        // 打开数据库
        function openDatabase() {
            return new Promise((resolve, reject) => {
                // 获取当前版本
                let currentVersion = getCurrentDBVersion();
                console.log('尝试打开数据库版本:', currentVersion);

                const request = indexedDB.open(DB_NAME, currentVersion);

                request.onerror = (event) => {
                    console.error('打开数据库失败:', event.target.error);
                    // 如果版本错误，尝试获取最新版本
                    if (event.target.error.name === 'VersionError') {
                        console.log('版本错误，尝试获取最新版本');
                        getLatestDBVersion().then(latestVersion => {
                            console.log('获取到最新版本:', latestVersion);
                            updateDBVersion(latestVersion);
                            // 重新尝试打开
                            const retryRequest = indexedDB.open(DB_NAME, latestVersion);
                            retryRequest.onsuccess = (retryEvent) => {
                                db = retryEvent.target.result;
                                console.log('数据库打开成功');
                                checkAndInitializeData().then(resolve).catch(reject);
                            };
                            retryRequest.onerror = (retryEvent) => {
                                console.error('重试打开数据库失败:', retryEvent.target.error);
                                reject(retryEvent.target.error);
                            };
                            retryRequest.onupgradeneeded = handleUpgradeNeeded;
                        }).catch(error => {
                            console.error('获取最新版本失败:', error);
                            reject(event.target.error);
                        });
                    } else {
                        reject(event.target.error);
                    }
                };

                request.onsuccess = (event) => {
                    db = event.target.result;
                    console.log('数据库打开成功');
                    // 更新版本号到localStorage
                    updateDBVersion(db.version);
                    // 检查并初始化数据
                    checkAndInitializeData().then(resolve).catch(error => {
                        console.error('检查初始化数据失败:', error);
                        resolve(); // 即使初始化检查失败也继续
                    });
                };

                request.onupgradeneeded = handleUpgradeNeeded;
            });
        }

        // 处理数据库升级
        function handleUpgradeNeeded(event) {
            console.log('数据库升级');
            const db = event.target.result;
            // 检查是否存在对象存储，如果不存在则创建
            if (!db.objectStoreNames.contains(STORE_NAME)) {
                console.log('创建对象存储:', STORE_NAME);
                const store = db.createObjectStore(STORE_NAME, { keyPath: 'id', autoIncrement: true });
                store.createIndex('text1', 'text1', { unique: false });
                store.createIndex('createtime', 'createtime', { unique: false });
            }
            // 更新版本号
            updateDBVersion(db.version);
        }

        // 获取数据库的最新版本
        function getLatestDBVersion() {
            return new Promise((resolve, reject) => {
                // 先不指定版本打开，获取当前版本
                const request = indexedDB.open(DB_NAME);

                request.onsuccess = (event) => {
                    const db = event.target.result;
                    const version = db.version;
                    db.close();
                    resolve(version);
                };

                request.onerror = (event) => {
                    console.error('获取数据库版本失败:', event.target.error);
                    reject(event.target.error);
                };
            });
        }

        // 绑定事件
        function bindEvents() {
            // 搜索按钮
            elements.searchBtn.addEventListener('click', () => {
                searchKeyword = elements.searchInput.value.trim();
                currentPage = 1;
                loadData();
            });

            // 重置按钮
            elements.resetBtn.addEventListener('click', () => {
                elements.searchInput.value = '';
                searchKeyword = '';
                currentPage = 1;
                loadData();
            });

            // 回车搜索
            elements.searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    searchKeyword = elements.searchInput.value.trim();
                    currentPage = 1;
                    loadData();
                }
            });

            // 新增
            elements.addBtn.addEventListener('click', () => {
                showEditModal();
            });

            // 统计
            if (STATS_BUTTON_ENABLED) {
                elements.statsBtn.addEventListener('click', () => {
                    showStatsModal();
                });
            }

            // 导入
            if (IMPORT_EXPORT_ENABLED) {
                elements.importBtn.addEventListener('click', () => {
                    showImportModal();
                });

                elements.importFileInput.addEventListener('change', (e) => {
                    importFile = e.target.files[0];
                    if (importFile) {
                        elements.importFileName.textContent = importFile.name;
                    } else {
                        elements.importFileName.textContent = '';
                    }
                });

                document.getElementById('confirm-import').addEventListener('click', () => {
                    importData();
                });

                document.getElementById('cancel-import').addEventListener('click', () => {
                    closeAllModals();
                });
            }

            // 导出
            if (IMPORT_EXPORT_ENABLED) {
                elements.exportBtn.addEventListener('click', () => {
                    exportData();
                });
            }

            // 分页
            elements.pageSize.addEventListener('change', () => {
                pageSize = parseInt(elements.pageSize.value);
                currentPage = 1;
                loadData();
            });

            elements.prevBtn.addEventListener('click', () => {
                if (currentPage > 1) {
                    currentPage--;
                    loadData();
                }
            });

            elements.nextBtn.addEventListener('click', () => {
                const totalPages = Math.ceil(totalRecords / pageSize);
                if (currentPage < totalPages) {
                    currentPage++;
                    loadData();
                }
            });

            // 跳转页面
            elements.jumpBtn.addEventListener('click', () => {
                jumpToPage();
            });

            elements.jumpInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    jumpToPage();
                }
            });

            // 表单提交
            elements.editForm.addEventListener('submit', (e) => {
                e.preventDefault();
                saveData();
            });

            // 弹窗关闭
            document.querySelectorAll('.close').forEach(closeBtn => {
                closeBtn.addEventListener('click', () => {
                    closeAllModals();
                });
            });

            document.getElementById('cancel-edit').addEventListener('click', () => {
                closeAllModals();
            });

            document.getElementById('close-detail').addEventListener('click', () => {
                closeAllModals();
            });

            document.getElementById('cancel-delete').addEventListener('click', () => {
                closeAllModals();
            });

            document.getElementById('confirm-delete').addEventListener('click', () => {
                deleteData();
            });

            document.getElementById('close-stats').addEventListener('click', () => {
                closeAllModals();
            });

            // 点击模态框外部关闭
            window.addEventListener('click', (e) => {
                if (e.target.classList.contains('modal')) {
                    closeAllModals();
                }
            });
        }

        // 跳转到指定页面
        function jumpToPage() {
            const totalPages = Math.ceil(totalRecords / pageSize);
            const page = parseInt(elements.jumpInput.value);
            if (page && page >= 1 && page <= totalPages) {
                currentPage = page;
                loadData();
            } else {
                alert(`请输入 1 到 ${totalPages} 之间的页码`);
            }
        }

        // 加载数据
        function loadData() {
            if (!db) return;

            const transaction = db.transaction([STORE_NAME], 'readonly');
            const store = transaction.objectStore(STORE_NAME);

            const request = store.getAll();

            request.onsuccess = () => {
                let allData = request.result;

                // 应用搜索过滤
                if (searchKeyword) {
                    allData = allData.filter(item =>
                        item.text1.toLowerCase().includes(searchKeyword.toLowerCase())
                    );
                }

                totalRecords = allData.length;

                // 排序（按创建时间倒序）
                allData.sort((a, b) => new Date(b.createtime) - new Date(a.createtime));

                // 分页
                const startIndex = (currentPage - 1) * pageSize;
                currentData = allData.slice(startIndex, startIndex + pageSize);

                // 渲染表格
                renderTable();
                updatePagination();
            };

            request.onerror = (event) => {
                console.error('加载数据失败:', event.target.error);
                alert('加载数据失败');
            };
        }

        // 渲染表格
        function renderTable() {
            elements.tableBody.innerHTML = '';

            if (currentData.length === 0) {
                const tr = document.createElement('tr');
                tr.innerHTML = `<td colspan="6" style="text-align: center; padding: 40px; color: #909399;">暂无数据</td>`;
                elements.tableBody.appendChild(tr);
                return;
            }

            currentData.forEach((item, index) => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td style="padding-left: 15px;">${ (currentPage - 1) * pageSize + index + 1 }</td>
                    <td>${escapeHtml(item.text1)}</td>
                    <td>${escapeHtml(item.text2)}</td>
                    <td>${escapeHtml(item.textarea1)}</td>
                    <td>${formatDate(item.createtime)}</td>
                    <td style="padding-right: 15px;" class="actions">
                        <button class="btn btn-sm btn-text" onclick="showDetail(${item.id})" title="明细查询">
                            <i class="fas fa-eye fa-icon"></i>
                            详情
                        </button>
                        <button class="btn btn-sm btn-warning" onclick="showEditModal(${item.id})">
                            <i class="fas fa-edit fa-icon"></i>
                            修改
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="showDeleteConfirm(${item.id})">
                            <i class="fas fa-trash fa-icon"></i>
                            删除
                        </button>
                    </td>
                `;
                elements.tableBody.appendChild(tr);
            });
        }

        // 更新分页信息
        function updatePagination() {
            const totalPages = Math.ceil(totalRecords / pageSize);
            const startRecord = totalRecords > 0 ? (currentPage - 1) * pageSize + 1 : 0;
            const endRecord = Math.min(currentPage * pageSize, totalRecords);

            elements.pageInfo.textContent = `显示第 ${startRecord} 到 ${endRecord} 条记录，共 ${totalRecords} 条记录`;

            // 更新按钮状态
            elements.prevBtn.classList.toggle('disabled', currentPage <= 1);
            elements.nextBtn.classList.toggle('disabled', currentPage >= totalPages);

            // 更新页码按钮
            renderPageNumbers(totalPages);

            // 更新跳转输入框
            elements.jumpInput.value = currentPage;
            elements.jumpInput.max = totalPages;
        }

        // 渲染页码按钮
        function renderPageNumbers(totalPages) {
            elements.pageNumbers.innerHTML = '';

            if (totalPages <= 1) return;

            const maxVisiblePages = 5;
            let startPage, endPage;

            if (totalPages <= maxVisiblePages) {
                // 显示所有页码
                startPage = 1;
                endPage = totalPages;
            } else {
                // 计算显示的页码范围
                const halfVisible = Math.floor(maxVisiblePages / 2);
                if (currentPage <= halfVisible) {
                    startPage = 1;
                    endPage = maxVisiblePages;
                } else if (currentPage + halfVisible >= totalPages) {
                    startPage = totalPages - maxVisiblePages + 1;
                    endPage = totalPages;
                } else {
                    startPage = currentPage - halfVisible;
                    endPage = currentPage + halfVisible;
                }
            }

            // 创建页码按钮
            for (let i = startPage; i <= endPage; i++) {
                const pageBtn = document.createElement('button');
                pageBtn.className = `page-btn ${i === currentPage ? 'active' : ''}`;
                pageBtn.textContent = i;
                pageBtn.onclick = () => {
                    currentPage = i;
                    loadData();
                };
                elements.pageNumbers.appendChild(pageBtn);
            }
        }

        // 显示编辑弹窗
        function showEditModal(id = null) {
            if (id) {
                // 修改模式
                const item = currentData.find(d => d.id === id);
                if (item) {
                    elements.editModalTitle.textContent = '修改数据';
                    elements.editId.value = item.id;
                    elements.editText1.value = item.text1;
                    elements.editText2.value = item.text2;
                    elements.editTextarea1.value = item.textarea1;
                }
            } else {
                // 新增模式
                elements.editModalTitle.textContent = '新增数据';
                elements.editId.value = '';
                elements.editText1.value = '';
                elements.editText2.value = '';
                elements.editTextarea1.value = '';
            }

            elements.editModal.style.display = 'block';
        }

        // 显示详情
        function showDetail(id) {
            const item = currentData.find(d => d.id === id);
            if (item) {
                elements.detailText1.textContent = item.text1;
                elements.detailText2.textContent = item.text2;
                elements.detailTextarea1.textContent = item.textarea1;
                elements.detailCreatetime.textContent = formatDate(item.createtime);
                elements.detailModal.style.display = 'block';
            }
        }

        // 显示删除确认
        function showDeleteConfirm(id) {
            deleteId = id;
            elements.deleteModal.style.display = 'block';
        }

        // 显示统计弹窗
        function showStatsModal() {
            elements.statsModal.style.display = 'block';
            drawChart();
        }

        // 显示导入弹窗
        function showImportModal() {
            elements.importFileInput.value = '';
            elements.importFileName.textContent = '';
            elements.importClearExisting.checked = false;
            elements.importModal.style.display = 'block';
        }

        // 绘制扇形图
        function drawChart() {
            const ctx = elements.statsChart.getContext('2d');
            ctx.clearRect(0, 0, elements.statsChart.width, elements.statsChart.height);

            // 获取统计数据
            getAllData().then(allData => {
                const stats = {};
                allData.forEach(item => {
                    const key = item.text1;
                    stats[key] = (stats[key] || 0) + 1;
                });

                const labels = Object.keys(stats);
                const values = Object.values(stats);
                const total = values.reduce((sum, val) => sum + val, 0);

                if (labels.length === 0) {
                    // 没有数据时显示提示
                    ctx.font = '16px Arial';
                    ctx.fillStyle = '#909399';
                    ctx.textAlign = 'center';
                    ctx.fillText('暂无数据', elements.statsChart.width / 2, elements.statsChart.height / 2);
                    elements.chartLegend.innerHTML = '';
                    return;
                }

                // 绘制扇形图
                const centerX = elements.statsChart.width / 2;
                const centerY = elements.statsChart.height / 2;
                const radius = Math.min(centerX, centerY) - 20;

                let startAngle = 0;

                // 清空图例
                elements.chartLegend.innerHTML = '';

                values.forEach((value, index) => {
                    const sliceAngle = (value / total) * 2 * Math.PI;
                    const endAngle = startAngle + sliceAngle;

                    // 绘制扇形
                    ctx.beginPath();
                    ctx.moveTo(centerX, centerY);
                    ctx.arc(centerX, centerY, radius, startAngle, endAngle);
                    ctx.closePath();
                    ctx.fillStyle = chartColors[index % chartColors.length];
                    ctx.fill();
                    ctx.strokeStyle = '#fff';
                    ctx.lineWidth = 2;
                    ctx.stroke();

                    // 添加图例
                    const legendItem = document.createElement('div');
                    legendItem.className = 'legend-item';
                    legendItem.innerHTML = `
                        <div class="legend-color" style="background-color: ${chartColors[index % chartColors.length]}"></div>
                        <div class="legend-text">${labels[index]}: ${value} (${((value / total) * 100).toFixed(1)}%)</div>
                    `;
                    elements.chartLegend.appendChild(legendItem);

                    startAngle = endAngle;
                });
            }).catch(error => {
                console.error('获取统计数据失败:', error);
                const ctx = elements.statsChart.getContext('2d');
                ctx.font = '16px Arial';
                ctx.fillStyle = '#909399';
                ctx.textAlign = 'center';
                ctx.fillText('加载数据失败', elements.statsChart.width / 2, elements.statsChart.height / 2);
            });
        }

        // 获取所有数据
        function getAllData() {
            return new Promise((resolve, reject) => {
                if (!db) {
                    reject('数据库未初始化');
                    return;
                }

                const transaction = db.transaction([STORE_NAME], 'readonly');
                const store = transaction.objectStore(STORE_NAME);
                const request = store.getAll();

                request.onsuccess = () => {
                    resolve(request.result);
                };

                request.onerror = (event) => {
                    console.error('获取所有数据失败:', event.target.error);
                    reject(event.target.error);
                };
            });
        }

        // 导出数据 - CSV格式
        function exportData() {
            getAllData().then(data => {
                // 创建CSV内容
                const headers = [COLUMN_TEXT1, COLUMN_TEXT2, COLUMN_TEXTAREA1, COLUMN_CREATETIME];
                let csvContent = '\uFEFF' + headers.join(',') + '\n'; // 添加BOM以支持中文

                data.forEach(item => {
                    const row = [
                        `"${escapeCsv(item.text1)}"`,
                        `"${escapeCsv(item.text2)}"`,
                        `"${escapeCsv(item.textarea1)}"`,
                        `"${escapeCsv(item.createtime)}"`
                    ];
                    csvContent += row.join(',') + '\n';
                });

                // 创建下载链接
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                const url = URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = `form_data_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.csv`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            }).catch(error => {
                console.error('导出数据失败:', error);
                alert('导出数据失败: ' + error);
            });
        }

        // 导入数据 - CSV格式
        function importData() {
            if (!importFile) {
                alert('请选择要导入的文件');
                return;
            }

            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    const csvContent = e.target.result;
                    const lines = csvContent.split('\n').filter(line => line.trim() !== '');

                    if (lines.length < 2) {
                        alert('文件内容为空或格式错误');
                        return;
                    }

                    // 解析CSV头部
                    const headers = lines[0].replace(/^\uFEFF/, '').split(',').map(h => h.trim().replace(/(^"|"$)/g, ''));

                    // 验证头部
                    if (headers[0] !== COLUMN_TEXT1 || headers[1] !== COLUMN_TEXT2 ||
                        headers[2] !== COLUMN_TEXTAREA1 || headers[3] !== COLUMN_CREATETIME) {
                        alert(`文件头部格式错误，应为: ${COLUMN_TEXT1},${COLUMN_TEXT2},${COLUMN_TEXTAREA1},${COLUMN_CREATETIME}`);
                        return;
                    }

                    // 解析数据行
                    const importData = [];
                    for (let i = 1; i < lines.length; i++) {
                        const line = lines[i].trim();
                        if (line) {
                            // 简单的CSV解析（处理引号包围的字段）
                            const values = parseCsvLine(line);
                            if (values.length >= 4) {
                                importData.push({
                                    text1: values[0],
                                    text2: values[1],
                                    textarea1: values[2],
                                    createtime: values[3]
                                });
                            }
                        }
                    }

                    if (importData.length === 0) {
                        alert('没有找到有效数据');
                        return;
                    }

                    // 确认导入
                    const clearExisting = elements.importClearExisting.checked;
                    const action = clearExisting ? '清空现有数据并导入' : '追加导入';
                    if (!confirm(`确定要${action} ${importData.length} 条数据吗？`)) {
                        return;
                    }

                    const transaction = db.transaction([STORE_NAME], 'readwrite');
                    const store = transaction.objectStore(STORE_NAME);

                    // 如果需要清空现有数据
                    if (clearExisting) {
                        const clearRequest = store.clear();
                        clearRequest.onsuccess = () => {
                            // 清空后插入新数据
                            insertImportedData(store, importData);
                        };
                        clearRequest.onerror = (event) => {
                            console.error('清空数据失败:', event.target.error);
                            alert('清空数据失败: ' + event.target.error);
                        };
                    } else {
                        // 直接插入数据
                        insertImportedData(store, importData);
                    }

                    transaction.oncomplete = () => {
                        closeAllModals();
                        loadData();
                        alert(`成功导入 ${importData.length} 条数据`);
                    };

                    transaction.onerror = (event) => {
                        console.error('导入数据失败:', event.target.error);
                        alert('导入数据失败: ' + event.target.error);
                    };

                } catch (error) {
                    console.error('解析文件失败:', error);
                    alert('解析文件失败：' + error.message);
                }
            };

            reader.onerror = () => {
                alert('读取文件失败');
            };

            reader.readAsText(importFile, 'utf-8');
        }

        // 解析CSV行
        function parseCsvLine(line) {
            const values = [];
            let currentValue = '';
            let inQuotes = false;

            for (let i = 0; i < line.length; i++) {
                const char = line[i];

                if (char === '"') {
                    if (inQuotes && i + 1 < line.length && line[i + 1] === '"') {
                        // 双引号转义
                        currentValue += '"';
                        i++; // 跳过下一个引号
                    } else {
                        // 切换引号状态
                        inQuotes = !inQuotes;
                    }
                } else if (char === ',' && !inQuotes) {
                    // 字段分隔符
                    values.push(currentValue);
                    currentValue = '';
                } else {
                    currentValue += char;
                }
            }

            values.push(currentValue);
            return values.map(value => value.replace(/(^"|"$)/g, '')); // 移除引号
        }

        // 转义CSV字段
        function escapeCsv(field) {
            if (typeof field === 'string') {
                // 替换双引号为两个双引号，并用双引号包围字段
                return field.replace(/"/g, '""');
            }
            return field;
        }

        // 插入导入的数据
        function insertImportedData(store, data) {
            data.forEach(item => {
                store.add(item);
            });
        }

        // 保存数据
        function saveData() {
            const id = elements.editId.value;
            const data = {
                text1: elements.editText1.value.trim(),
                text2: elements.editText2.value.trim(),
                textarea1: elements.editTextarea1.value.trim(),
                createtime: id ? currentData.find(d => d.id == id).createtime : new Date().toISOString()
            };

            if (!data.text1 || !data.text2 || !data.textarea1) {
                alert('请填写所有必填字段');
                return;
            }

            const transaction = db.transaction([STORE_NAME], 'readwrite');
            const store = transaction.objectStore(STORE_NAME);

            if (id) {
                // 修改
                data.id = parseInt(id);
                store.put(data);
            } else {
                // 新增
                store.add(data);
            }

            transaction.oncomplete = () => {
                closeAllModals();
                loadData();
            };

            transaction.onerror = (event) => {
                console.error('保存数据失败:', event.target.error);
                alert('保存数据失败: ' + event.target.error);
            };
        }

        // 删除数据
        function deleteData() {
            if (!deleteId) return;

            const transaction = db.transaction([STORE_NAME], 'readwrite');
            const store = transaction.objectStore(STORE_NAME);
            const request = store.delete(deleteId);

            request.onsuccess = () => {
                closeAllModals();
                // 如果当前页没有数据了，回到上一页
                if (currentData.length === 1 && currentPage > 1) {
                    currentPage--;
                }
                loadData();
            };

            request.onerror = (event) => {
                console.error('删除数据失败:', event.target.error);
                alert('删除数据失败: ' + event.target.error);
            };
        }

        // 关闭所有弹窗
        function closeAllModals() {
            elements.editModal.style.display = 'none';
            elements.detailModal.style.display = 'none';
            elements.deleteModal.style.display = 'none';
            elements.statsModal.style.display = 'none';
            elements.importModal.style.display = 'none';
            deleteId = null;
            importFile = null;
        }

        // 检查并初始化数据
        function checkAndInitializeData() {
            return new Promise((resolve, reject) => {
                if (!db) {
                    console.log('数据库未初始化');
                    reject('数据库未初始化');
                    return;
                }

                console.log('检查数据库对象存储');

                // 检查对象存储是否存在
                if (!db.objectStoreNames.contains(STORE_NAME)) {
                    console.log('对象存储不存在，需要升级数据库');
                    // 如果对象存储不存在，需要升级数据库
                    const currentVersion = db.version;
                    const newVersion = currentVersion + 1;
                    db.close();

                    console.log('关闭当前连接，重新打开数据库进行升级');
                    const upgradeRequest = indexedDB.open(DB_NAME, newVersion);

                    upgradeRequest.onsuccess = (event) => {
                        console.log('升级成功');
                        db = event.target.result;
                        // 更新版本号
                        updateDBVersion(newVersion);
                        // 升级成功后初始化数据
                        performDataInitialization().then(resolve).catch(reject);
                    };

                    upgradeRequest.onupgradeneeded = (event) => {
                        console.log('执行升级操作');
                        const upgradedDb = event.target.result;
                        if (!upgradedDb.objectStoreNames.contains(STORE_NAME)) {
                            console.log('创建新的对象存储');
                            const store = upgradedDb.createObjectStore(STORE_NAME, { keyPath: 'id', autoIncrement: true });
                            store.createIndex('text1', 'text1', { unique: false });
                            store.createIndex('createtime', 'createtime', { unique: false });
                        }
                    };

                    upgradeRequest.onerror = (event) => {
                        console.error('数据库升级失败:', event.target.error);
                        reject(event.target.error);
                    };
                } else {
                    console.log('对象存储存在，检查数据');
                    // 对象存储存在，检查是否有数据
                    try {
                        const transaction = db.transaction([STORE_NAME], 'readonly');
                        const store = transaction.objectStore(STORE_NAME);
                        const countRequest = store.count();

                        countRequest.onsuccess = () => {
                            console.log('数据条数:', countRequest.result);
                            if (countRequest.result === 0) {
                                console.log('无数据，进行初始化');
                                // 如果没有数据，插入初始化数据
                                performDataInitialization().then(resolve).catch(reject);
                            } else {
                                console.log('已有数据，无需初始化');
                                resolve();
                            }
                        };

                        countRequest.onerror = (event) => {
                            console.error('检查数据数量失败:', event.target.error);
                            // 即使检查失败也继续
                            resolve();
                        };
                    } catch (error) {
                        console.error('创建事务失败:', error);
                        resolve(); // 即使检查失败也继续
                    }
                }
            });
        }

        // 执行数据初始化
        function performDataInitialization() {
            return new Promise((resolve, reject) => {
                console.log('开始初始化数据');
                if (!db) {
                    reject('数据库连接已断开');
                    return;
                }

                try {
                    const transaction = db.transaction([STORE_NAME], 'readwrite');
                    const store = transaction.objectStore(STORE_NAME);

                    // 插入初始化数据
                    INITIAL_DATA.forEach(data => {
                        store.add(data);
                    });

                    transaction.oncomplete = () => {
                        console.log('初始化数据插入完成');
                        resolve();
                    };

                    transaction.onerror = (event) => {
                        console.error('初始化数据插入失败:', event.target.error);
                        reject(event.target.error);
                    };
                } catch (error) {
                    console.error('初始化数据时发生错误:', error);
                    reject(error);
                }
            });
        }

        // 工具函数：转义HTML
        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '<',
                '>': '>',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, m => map[m]);
        }

        // 工具函数：格式化日期
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            getConfig();
            setInitData();
            initApp();
        });

        // 全局函数供HTML调用
        window.showDetail = showDetail;
        window.showEditModal = showEditModal;
        window.showDeleteConfirm = showDeleteConfirm;
    </script>
</body>

</html>